package comunicacion;

import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.*;

public class Cliente {
	private Socket socket;
	private int puerto;
	private String ip = "localhost";
	
	private ObjectOutputStream writerObject;
	private ObjectInputStream readerObject;
	
	private DataInputStream readerData;
	private DataOutputStream writerData;
	
	private boolean hayConexion = false;

	public Cliente(){
	}
	
	public Cliente(String ip){
		this.ip = ip;
	}
	
	public Cliente(String ip, int puerto){
		this.ip = ip;
		this.puerto = puerto;
	}
	
	public void createClient() {
		//System.out.println("setupNetworking!");
		try {
			socket = new Socket(ip, puerto);
			writerObject = new ObjectOutputStream(socket.getOutputStream());
			readerObject = new ObjectInputStream(socket.getInputStream());
			writerData = new DataOutputStream(socket.getOutputStream());
			readerData = new DataInputStream(socket.getInputStream());
			hayConexion = true;
//			System.out.println("Cliente dice => Me conecte al servidor: " + socket.getInetAddress() + 
//					"  Hostname:" + socket.getInetAddress().getHostName());
		} 
		catch (UnknownHostException e) {
			e.printStackTrace();
			System.out.println("@client: Error de Conexion! #2" + "\n");
		} 
		catch (IOException e) {
			e.printStackTrace();
			System.out.println("@client: Error de Conexion! #1" + "\n");
		}
	}
	
	public Mensaje readObject(){
		try {
			return (Mensaje) readerObject.readObject();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public void sendObject(Mensaje mensaje){
		try {
			writerObject.writeObject(mensaje);
			writerObject.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int readDataInt(){
		try {
			return readerData.readInt();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -9;
		}
	}
	
	public void sendDataInt(int port){
		try {
			writerData.writeInt(port);
			writerData.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void close(){
		try {
			writerObject.close();
			readerObject.close();
			writerData.close();
			readerData.close();
			socket.close();
			hayConexion = false;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public InetAddress getInetAddress(){
		return socket.getInetAddress();
	}
	
	public boolean hayConexion(){
		return hayConexion;
	}
}